

#define _WINSOCK2API_
#define _WINSOCKAPI_

#include <string.h>
#include <Windows.h>
#include <GdiPlus.h>
using namespace Gdiplus;

#include "tp_typedef.h"
#include "tp_image_decoder_win32.h"
#include "tp_memory.h"

static ULONG_PTR g_gdiPlusToken = 0;

static TpRet tp_image_decoder_win32_match(TpImageDecoder* thiz, const char* file)
{
	if (NULL == file) return TP_RET_FAIL;

	return (strstr(file, ".bmp") != NULL ||
            strstr(file, ".jpg") != NULL ||
			strstr(file, ".jpeg") != NULL ||
            strstr(file, ".gif") != NULL) ? TP_RET_OK : TP_RET_FAIL;
			/* strstr(file, ".png") != NULL) ? TP_RET_OK : TP_RET_FAIL; */
}

static void tp_image_decoder_win32_destroy(TpImageDecoder* thiz)
{
	if (NULL != thiz) tp_free(thiz);

	GdiplusShutdown(g_gdiPlusToken);

	return;
}

static TpBitmap* tp_image_decoder_win32_decode(TpImageDecoder* thiz, const char* file)
{
	TpBitmap* bitmap = NULL;

	int i, j;
	int w, h;
	TpColor color = {0};
	TpColor* src = NULL;
	TpColor* dst = NULL;

	WCHAR path[MAX_PATH];
	mbstowcs(path, file, strlen(file));

	Bitmap bmp(path, FALSE);
	BitmapData bmpData;

	w = bmp.GetWidth();
	h = bmp.GetHeight();

	Rect bmpRect(0, 0, w, h);

	bitmap = tp_bitmap_create(w, h, &color);

	bmp.LockBits(&bmpRect, ImageLockModeRead, PixelFormat32bppARGB, &bmpData);

	src = (TpColor*)bmpData.Scan0;
	dst = tp_bitmap_bits(bitmap);

	for (i = 0; i < h; ++i)
	{
		for (j = 0; j < w; ++j)
		{
			*dst = *src;
			
			++src;
			++dst;
		}
	}

	bmp.UnlockBits(&bmpData);

	return bitmap;
}

TpImageDecoder* tp_image_decoder_win32_create(void)
{
	TpImageDecoder* thiz = (TpImageDecoder*)tp_alloc(sizeof(TpImageDecoder));
	if (NULL != thiz)
	{
		GdiplusStartupInput gdiPlusInput;
		GdiplusStartup(&g_gdiPlusToken, &gdiPlusInput, NULL);

		thiz->match = tp_image_decoder_win32_match;
		thiz->decode = tp_image_decoder_win32_decode;
		thiz->destroy = tp_image_decoder_win32_destroy;
	}

	return thiz;
}
